package xyz.scootaloo.mono.admin.web.auth

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import xyz.scootaloo.mono.admin.dto.PageInfo
import xyz.scootaloo.mono.admin.dto.QuickUserFormVO
import xyz.scootaloo.mono.admin.dto.SysUserVO
import xyz.scootaloo.mono.admin.dto.UpdateUserFormVO
import xyz.scootaloo.mono.admin.service.auth.UserManageService
import xyz.scootaloo.mono.base.lang.R
import xyz.scootaloo.mono.base.lang.SC
import javax.servlet.http.HttpServletRequest

/**
 * 用户管理接口
 *
 * - 获取用户信息列表(分页显示) [listUserInfo]
 * - 搜索用户信息(根据用户名查找) [searchUserByName]
 * - 快速创建用户 [quicklyCreateUser]
 * - 禁用用户账号 [disableUserAccount]
 * - 重新分配用户角色 [distributeRolesToUser]
 * - 更新用户信息 [updateUserInfo]
 * - 获取指定编号的用户信息 [getUserInfo]
 * - 删除指定编号的用户账号 [deleteUser]
 *
 * @author flutterdash@qq.com
 * @since 2021/9/3 12:10
 */
@RestController
@RequestMapping("/admin/user")
class UserAdminController {

    @Autowired lateinit var userManager: UserManageService

    @GetMapping("/list/{pageNum}/{pageSize}")
    fun listUserInfo(
        @PathVariable pageNum: Int, @PathVariable pageSize: Int
    ): R<PageInfo<SysUserVO>> = R.tryAndGet { userManager.list(pageNum, pageSize) }

    @GetMapping("/s/{name}")
    fun searchUserByName(@PathVariable name: String): R<List<SysUserVO>> =
        R.tryAndGet { userManager.search(name) }

    @PostMapping("/create/quickly")
    fun quicklyCreateUser(@RequestBody user: QuickUserFormVO, request: HttpServletRequest): R<Unit> =
        R.tryAndGet(SC.FAILED) { userManager.create(user, request) }

    @GetMapping("/disable/{uid}")
    fun disableUserAccount(@PathVariable uid: Int, request: HttpServletRequest): R<Unit> =
        R.tryAndGet(SC.FAILED) { userManager.disable(uid, request) }

    @PostMapping("/roles/{uid}")
    fun distributeRolesToUser(
        @PathVariable uid: Int, @RequestBody roles: List<Int>, request: HttpServletRequest
    ): R<Unit> = R.tryAndGet(SC.FAILED) { userManager.distributeRoles(uid, roles, request) }

    @PutMapping("/update")
    fun updateUserInfo(@RequestBody user: UpdateUserFormVO): R<Unit> =
        R.tryAndGet { userManager.updateInfo(user) }

    @GetMapping("/user-info/{uid}")
    fun getUserInfo(@PathVariable uid: Int): R<UpdateUserFormVO> =
        R.tryAndGet { userManager.getInfo(uid) }

    @DeleteMapping("/{uid}")
    fun deleteUser(@PathVariable uid: Int, request: HttpServletRequest): R<Unit> =
        R.tryAndGet { userManager.delete(uid, request) }
}
